import { defineComponent, reactive, ref, onMounted, watch } from 'vue'
// import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import {
  ElButton,
  ElRadioGroup,
  ElRadio,
  ElInput,
  ElSelect,
  ElOption,
  ElLink,
  ElCard,
  ElSpace,
  ElIcon,
  ElMessage,
  ElDatePicker,
  ElLoading
} from 'element-plus'
import { Plus, MapLocation } from '@element-plus/icons-vue'

import type { personInChargeEnum, patrolTypeEnum } from '~/store/oam/tour/typings'
import type { TableColumnProps, ProSaasTableExposeType } from '~/components/ProSaasTable/typings'
import type {
  ValuesType,
  SystemUserOptionsPropsType,
  TaskPropsType,
  CourtsType,
  mapViewPropsType,
  mapViewRoadData,
  mapMarderViewPropsType,
  MapRefViewType,
  TourPlanCompilePropsType,
  RoadType
} from './typings'

import styles from './index.module.scss'
import useVuexGetters from '~/hooks/useVuexGetters'
import AliIcon from '~/components/AliIocn'
import SaasTitle from '~/components/SaasTitle'
import MapView from './map'
import ProSaasTable from '~/components/ProSaasTable'
import CourtsView from './courts'
import TaskDetails from './taskDetails'
import MapInfoView from './mapInfoView'
import RoadMap from './roadMap'
import RoadSelect from './roadSelect'

export default defineComponent({
  name: 'TourPlanCompile',
  props: ['id', 'type', 'goBack'],
  setup(props: TourPlanCompilePropsType) {
    const store = useStore()
    const state = reactive<SystemUserOptionsPropsType>({
      courtVisible: false,
      roadVisible: false,
      moduleId: '',
      list: [] as any[],
      type: ''
    })
    const taskState = reactive<TaskPropsType>({
      visible: false,
      list: []
    })
    const time = reactive({
      list: [] as any[]
    })
    const list = reactive({
      value: [] as any[]
    })
    const mapstate = reactive<mapMarderViewPropsType>({
      id: 'mapView',
      visible: false,
      markers: []
    })
    const mapData = reactive<mapViewPropsType>({
      id: 'ordersUpdateMapr',
      markers: []
    })
    const roadMapData = reactive<mapViewRoadData>({
      roadData: [],
      id: 'roadMap'
    })
    // const router = useRouter()
    const proSaasTableRef = ref<ProSaasTableExposeType>()
    const formValues = reactive<ValuesType>({})
    const mapRefView = ref<MapRefViewType>()
    const mapRoadRefView = ref()
    const tourState = useVuexGetters('tour', ['personInChargeOpt', 'patrolTypeOpt'])
    const columns: TableColumnProps<CourtsType>[] = [
      {
        label: '台区名称',
        prop: 'assetName',
        showOverflowTooltip: true,
        minWidth: 100
      },
      {
        label: '所属工区',
        prop: 'workAreaName',
        showOverflowTooltip: true,
        minWidth: 100
      },
      {
        label: '台区地址',
        prop: 'assetAddress',
        showOverflowTooltip: true,
        minWidth: 100
      },
      {
        label: '操作',
        prop: 'options',
        minWidth: 120,
        unFixed: true,
        fixed: 'right',
        render: ({ row }) => (
          <ElSpace>
            <ElLink icon={MapLocation} type="primary" onClick={() => mapInfo(row)}>
              &nbsp;地图
            </ElLink>
          </ElSpace>
        )
      }
    ]
    const roadcolumns: TableColumnProps<RoadType>[] = [
      {
        label: '道路名称',
        prop: 'assetName',
        showOverflowTooltip: true,
        minWidth: 100
      },
      {
        label: '所属区域',
        prop: 'workAreaName',
        showOverflowTooltip: true,
        minWidth: 100
      },
      {
        label: '关联灯具',
        prop: 'lampCount',
        showOverflowTooltip: true,
        minWidth: 100
      }
    ]

    onMounted(async () => {
      store.dispatch('tour/GetPatrolHandleUser')
      const { code, data } = await store.dispatch('tour/GetConfigList')
      if (code === 200) {
        if (data.length > 0) {
          formValues.configId = data[0].id
          radioChange(formValues.configId)
        }
      }
      // const { type } = router.currentRoute.value.query
      if (props.type !== 'add') {
        info()
      }
    })
    watch(
      () => list.value,
      (newVal) => {
        if (state.type === '台区') {
          const array: { id: any; latitude: any; longitude: any }[] = []
          if (newVal.length > 0) {
            newVal.forEach((item) => {
              if (item.phase) {
                const phase = JSON.parse(item.phase)
                array.push({
                  id: item.assetId,
                  longitude: Number(phase.coordinates[0]),
                  latitude: Number(phase.coordinates[1])
                })
              }
            })
            mapData.markers = array
            mapRefView.value!?.loopMarker()
          } else {
            mapData.markers = []
          }
        } else {
          roadMapData.roadData = newVal
          mapRoadRefView.value!?.searchRoad()
        }
      }
    )
    //  详情
    const info = async () => {
      // const { id } = router.currentRoute.value.query
      const { code, data } = await store.dispatch('tour/PatrolGroupView', { id: props.id })
      if (code === 200) {
        formValues.configId = data.configId
        formValues.name = data.name
        formValues.leadUserId = data.leadUserId
        formValues.leadUserName = data.leadUserName
        formValues.leadDeptId = data.leadDeptId
        formValues.leadDeptName = data.leadDeptName
        formValues.typeName = data.typeName
        if (data.groupDetailList.length > 0) {
          list.value = data.groupDetailList
        }
        state.moduleId = data.configId
        cycleAjax(data.configId)
        radioChange(data.configId)
      }
    }
    //  显示地图
    const mapInfo = (row: any) => {
      if (!row.phase) {
        ElMessage({ type: 'warning', message: '当前台区未上传定位信息' })
        return
      }
      const array: { id: any; latitude: any; longitude: any }[] = []
      const phase = JSON.parse(row.phase)
      array.push({
        id: row.assetId,
        longitude: Number(phase.coordinates[0]),
        latitude: Number(phase.coordinates[1])
      })
      mapstate.markers = array
      mapstate.visible = !mapstate.visible
    }
    //  关闭地图
    const mapMarkerCancel = () => {
      mapstate.visible = !mapstate.visible
    }
    //  返回
    const goBack = () => {
      // router.go(-1)
      props.goBack!()
    }
    //  巡视类型选择
    const radioChange = async (value: any) => {
      if (value !== state.moduleId) list.value = []
      tourState.patrolTypeOpt?.value?.forEach((item: any) => {
        if (item.id === value) {
          cycleAjax(item.id)
          formValues.moduleId = item.moduleId
          state.moduleId = item.moduleId
          formValues.typeName = item.typeName
        }
        if (value === '1606223397243109377') {
          state.type = '台区'
        } else if (value === '1606223397243109378') {
          state.type = '道路'
        }
      })
    }

    //  请求最近五次任务周期
    const cycleAjax = async (id: any) => {
      const { code, data } = await store.dispatch('tour/GenerateCycle', { id })
      if (code === 200) {
        const time1 = data[0].split('——')[0].replace('年', '').replace('月', '').replace('日', '')
        const time2 = data[data.length - 1]
          .split('——')[1]
          .replace('年', '')
          .replace('月', '')
          .replace('日', '')
        time.list.push(time1)
        time.list.push(time2)
        taskState.list = data
      }
    }
    const linkOpen = () => {
      if (state.moduleId === '') {
        ElMessage({ type: 'warning', message: '请选择巡视类型' })
        return
      }
      taskState.visible = !taskState.visible
    }
    //  新增台区/道路
    const add = () => {
      if (state.moduleId === '') {
        ElMessage({ type: 'warning', message: '请选择巡视类型' })
        return
      }
      if (formValues.configId === '1606223397243109377' || state.type === '台区')
        state.courtVisible = !state.courtVisible
      if (formValues.configId === '1606223397243109378' || state.type === '道路')
        state.roadVisible = !state.roadVisible
    }
    //  确定台区/道路
    const courtsSubmit = (row: any) => {
      list.value = row
    }
    //  删除台区
    const del = () => {
      const ids = proSaasTableRef.value!.selecteds?.map?.((item) => item!?.assetId)?.join(',')

      if (!ids) {
        ElMessage({ type: 'warning', message: '请勾选删除数据' })
        return
      }
      const array = []
      for (let i = 0; i < list.value.length; i++) {
        const item = list.value[i]
        if (ids.indexOf(item.assetId) === -1) {
          array.push(item)
        }
      }
      list.value = array
    }
    //  选择责任人
    const leadUserChange = (value: any) => {
      tourState.personInChargeOpt?.value.forEach((item: personInChargeEnum) => {
        if (item.id === value) {
          formValues.leadUserName = item.realName
          formValues.leadDeptId = item.leadDeptId
          formValues.leadDeptName = item.leadDeptName
        }
      })
    }
    //  提交
    const confirm = async () => {
      if (!formValues.configId) {
        ElMessage({ type: 'warning', message: '请选择巡视类型' })
        return
      }
      if (!formValues.name) {
        ElMessage({ type: 'warning', message: '请输入巡视名称' })
        return
      }
      if (!formValues.leadUserId) {
        ElMessage({ type: 'warning', message: '请选择责任人' })
        return
      }
      if (list.value.length === 0) {
        ElMessage({ type: 'warning', message: '请选择台区' })
        return
      }
      const loading = ElLoading.service({
        target: '#compile',
        lock: true,
        text: '提交中'
      })
      const params = {
        configId: formValues.configId,
        name: formValues.name,
        leadUserId: formValues.leadUserId,
        leadUserName: formValues.leadUserName,
        leadDeptId: formValues.leadDeptId,
        leadDeptName: formValues.leadDeptName,
        moduleId: formValues.moduleId,
        groupDetailList: list.value,
        typeName: formValues.typeName
      }
      // const { id } = router.currentRoute.value.query
      const { id } = props
      let url = ''
      if (id) {
        url = 'tour/PatrolGroupSave'
      } else {
        url = 'tour/patrolGroupAdd'
      }
      const { code } = await store.dispatch(url, { ...params, id })
      if (code === 200) {
        loading.close()
        ElMessage({ type: 'success', message: '操作成功' })
        goBack()
      } else {
        loading.close()
      }
    }

    return () => {
      // const { type } = router.currentRoute.value.query
      return (
        <ElCard class={styles['compile-card']}>
          <ElSpace class={styles['compile-tab-option-btns']}>
            <ElButton text type="primary" onClick={goBack}>
              返回上一级&nbsp;
              <AliIcon type="icon-fanhuishangyiji" />
            </ElButton>
          </ElSpace>
          <div class={styles.form}>
            {props.type !== 'read' && (
              <div class={styles.form_bd}>
                <div class={styles.form_bd_input}>
                  <div class={styles.label}>巡视类型选择：</div>
                  <div class={styles.input}>
                    <ElRadioGroup v-model={formValues.configId} onChange={radioChange}>
                      {tourState.patrolTypeOpt?.value?.map((item: patrolTypeEnum) => (
                        <ElRadio label={item?.id} size="large">
                          {item?.typeName}
                        </ElRadio>
                      ))}
                    </ElRadioGroup>
                  </div>
                </div>
              </div>
            )}
            <div class={styles.form_bd}>
              <div class={styles.form_bd_input}>
                <div class={styles.label}>
                  {props.type !== 'read' && <span>*</span>}
                  巡视名称：
                </div>
                <div class={styles.input}>
                  {props.type !== 'read' ? (
                    <ElInput
                      v-model={formValues.name}
                      placeholder="请输入"
                      {...{ maxlength: 30 }}
                    />
                  ) : (
                    formValues.name
                  )}
                </div>
              </div>
              <div class={styles.form_bd_input}>
                <div class={styles.label}>
                  {props.type !== 'read' && <span>*</span>}
                  责任人：
                </div>
                <div class={styles.input}>
                  {props.type !== 'read' ? (
                    <ElSelect v-model={formValues.leadUserId} onChange={leadUserChange} clearable>
                      {tourState.personInChargeOpt?.value?.map((item: personInChargeEnum) => (
                        <ElOption key={item?.id} label={item?.realName} value={item?.id} />
                      ))}
                    </ElSelect>
                  ) : (
                    formValues.leadUserName
                  )}
                </div>
              </div>
              <div class={styles.form_bd_input}>
                <div class={styles.label}>巡视任务生成周期：</div>
                <div class={styles.input}>
                  {props.type !== 'read' ? (
                    <ElDatePicker
                      v-model={time.list}
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      valueFormat="YYYY-MM-DD"
                      format="YYYY-MM-DD"
                      type="daterange"
                      disabled
                    />
                  ) : (
                    `${time.list[0]}--${time.list[1]}`
                  )}
                </div>
                <ElLink type="primary" class={styles.text} onClick={linkOpen}>
                  <AliIcon type="icon-chakan" />
                  &nbsp; 查看巡视任务生成明细
                </ElLink>
              </div>
            </div>
            <div class={styles.form_con}>
              <div class={styles.form_item}>
                <SaasTitle type="primary">
                  <ElLink underline={false}>
                    {state.type === '台区' || formValues.typeName === '台区巡视'
                      ? '台区列表'
                      : '道路列表'}
                  </ElLink>
                </SaasTitle>
                <div style="width: 100px; height: 16px;"></div>
                <ProSaasTable
                  ref={proSaasTableRef}
                  columns={state.type === '台区' ? columns : roadcolumns}
                  data={list.value}
                  hasSelection
                  height="545px"
                  needPagination={false}
                  headerTitle={
                    <>
                      <ElButton type="primary" disabled={props.type === 'read'} onClick={add}>
                        <ElIcon>
                          <Plus />
                        </ElIcon>
                        &nbsp; 新增
                      </ElButton>
                      <ElButton type="danger" disabled={props.type === 'read'} onClick={del}>
                        <AliIcon type="icon-shanchu" />
                        &nbsp; 删除
                      </ElButton>
                    </>
                  }
                ></ProSaasTable>
              </div>
              <div class={styles.form_map}>
                {(state.type === '台区' || formValues.typeName === '台区巡视') && (
                  <MapView id={mapData.id} ref={mapRefView} setFitView markers={mapData.markers} />
                )}
                {(state.type === '道路' || formValues.typeName === '道路巡视') && (
                  <RoadMap
                    id={roadMapData.id}
                    setFitView
                    ref={mapRoadRefView}
                    roadData={roadMapData.roadData}
                  />
                )}
              </div>
            </div>
          </div>
          <div class={styles.footer}>
            <div class={styles.bor}></div>
            <div class={styles.btn}>
              <ElButton onClick={goBack}>取消</ElButton>
              {props.type !== 'read' && (
                <ElButton type="primary" onClick={confirm}>
                  确定
                </ElButton>
              )}
            </div>
          </div>
          {/* 选择台区 */}
          {state.courtVisible && (
            <CourtsView
              visible={state.courtVisible}
              onCancel={add}
              onConfirm={courtsSubmit}
              moduleId={state.moduleId}
              list={list.value}
            />
          )}
          {/* 选择道路 */}
          {state.roadVisible && (
            <RoadSelect
              visible={state.roadVisible}
              onCancel={add}
              onConfirm={courtsSubmit}
              moduleId={state.moduleId}
              list={list.value}
            />
          )}
          {/* 查看巡视任务生成明细 */}
          {taskState.visible && (
            <TaskDetails visible={taskState.visible} onCancel={linkOpen} list={taskState.list} />
          )}
          {/* 查看地图 */}
          {mapstate.visible && (
            <MapInfoView
              id={mapstate.id}
              visible={mapstate.visible}
              onCancel={mapMarkerCancel}
              markers={mapstate.markers}
            />
          )}
        </ElCard>
      )
    }
  }
})
